package com.example.demo.controller;

import com.example.demo.common.RestResult;
import com.example.demo.model.Question;
import com.example.demo.service.CozeService;
import com.example.demo.service.QuestionServiceMongo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.HashMap;
import java.util.Map;

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/ask")
public class AskController {
    private static final Logger logger = LoggerFactory.getLogger(AskController.class);

    private final CozeService cozeService;
    private final QuestionServiceMongo questionService;

    public AskController(CozeService cozeService, QuestionServiceMongo questionService) {
        this.cozeService = cozeService;
        this.questionService = questionService;
    }

    @PostMapping(value = "/questionV2", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    @PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
    public SseEmitter askQuestionStream(@RequestBody Map<String, String> request) {
        String question = request.get("question");
        if (question == null || question.trim().isEmpty()) {
            SseEmitter errorEmitter = new SseEmitter(0L);
            try {
                errorEmitter.send(SseEmitter.event().name("error").data("问题不能为空"));
            } catch (Exception ignored) {}
            errorEmitter.complete();
            return errorEmitter;
        }

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        String username = userDetails.getUsername();

        logger.info("[SSE] User {} asked(questionV2): {}", username, question);

        SseEmitter emitter = new SseEmitter(0L);
        cozeService.streamWorkflowEvents(question, emitter);
        return emitter;
    }
    @PostMapping("/question")
    @PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
    public RestResult<Map<String, Object>> askQuestion(@RequestBody Map<String, String> request) {
        try {
            String question = request.get("question");
            if (question == null || question.trim().isEmpty()) {
                return RestResult.error("问题不能为空");
            }

            // 获取当前登录用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            String username = userDetails.getUsername();

            logger.info("User {} asked: {}", username, question);

            // 调用Coze API获取回答
            String answer = cozeService.askQuestion(question);

            // 保存问题和回答
            Question savedQuestion = questionService.saveQuestion(username, question, answer);

            Map<String, Object> response = new HashMap<>();
            response.put("question", question);
            response.put("answer", answer);
            if (savedQuestion != null) {
                response.put("id", savedQuestion.getId());
                response.put("timestamp", savedQuestion.getCreatedAt().toString());
            }

            return RestResult.success(response);
        } catch (Exception e) {
            logger.error("Error processing question", e);
            return RestResult.error("处理问题时出错");
        }
    }

    // 获取用户问题历史，支持按提问人和问题内容查询，按创建时间倒序排列，支持分页
    @GetMapping("/history")
    // @PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
    @PreAuthorize("hasRole('ADMIN')")
    public RestResult<Page<Question>> getQuestionHistory(
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String questionText,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            // 创建分页参数，按创建时间倒序排列
            Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "createdAt"));

            // 调用服务层方法分页查询问题历史
            Page<Question> questionsPage = questionService.getQuestionsByUsernameAndKeywordOrderByCreatedAtDescWithPagination(username, questionText, pageable);

            logger.info("Retrieved page {} of questions (size: {}) for username: {}, questionText: {}",
                    page, size, username, questionText);

            return RestResult.success(questionsPage);
        } catch (Exception e) {
            logger.error("Error retrieving question history with pagination", e);
            return RestResult.error("获取问题历史时出错");
        }
    }
}
